home *** CD-ROM | disk | FTP | other *** search
/ Amiga Collections: Camelot / Camelot 059 (1989-12)(Swedish User Group of Amiga)(SE)(PD)[WB].zip / Camelot 059 (1989-12)(Swedish User Group of Amiga)(SE)(PD)[WB].adf / Utils / tee.c < prev    next >
C/C++ Source or Header  |  1989-11-14  |  2KB  |  96 lines

  1. /*
  2. tee file1 file2 ...
  3.  
  4. copies standard input to standard output and file1, file2, ...
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <error.h>
  11. #include <ios1.h>
  12. #include <proto/dos.h>
  13.  
  14. #define STR(x) # x
  15.  
  16. #define TRUE 1
  17. #define FALSE 0
  18.  
  19. #define WARN 10
  20. #define ERROR 20
  21.  
  22. #define MAXLEN 256 /* Max line length */
  23. #define MAXF 10
  24.  
  25. extern int _bufsiz;
  26. int err;
  27.  
  28. void main(int argc, char **argv)
  29. {
  30.     FILE *files[MAXF];
  31.     int i, f, nb;
  32.     char line[MAXLEN + 1], *mode;
  33.  
  34.     /* Setup stdout */
  35.     if (IsInteractive(chkufb(fileno(stdout))->ufbfh))
  36.         setvbuf(stdout, NULL, _IOLBF, _bufsiz);
  37.  
  38.     if (argc >= 2 && strcmp(argv[1], "-a") == 0)
  39.     {
  40.         argc--;
  41.         argv++;
  42.         mode = "a";
  43.     }
  44.     else
  45.         mode = "w";
  46.  
  47.     if (argc > MAXF)
  48.     {
  49.         fputs("No more than " STR(MAXF) " files\n", stderr);
  50.         nb = MAXF;
  51.     }
  52.     else
  53.         nb = argc;
  54.  
  55.     for (i = 1, f = 0; i < nb; i++)
  56.     {
  57.         files[f] = fopen(argv[i], mode);
  58.  
  59.         if (!files[f])
  60.         {
  61.             char buf[81];
  62.  
  63.             buf[80] = '\0';
  64.             strcpy(buf, "Error opening ");
  65.             strncat(buf, argv[i], 80 - strlen(buf));
  66.             perror(buf);
  67.             fflush(stderr);
  68.             err = WARN;
  69.         }
  70.         else
  71.             f++;
  72.     }
  73.  
  74.     line[MAXLEN] = '\0';
  75.     while (fgets(line, MAXLEN, stdin) && err < ERROR)
  76.     {
  77.         fputs(line, stdout);
  78.         for (i = 0; i < f && err < ERROR; i++)
  79.         {
  80.             fputs(line, files[i]);
  81.             if (errno != 0) err = ERROR;
  82.         }
  83.     }
  84.     fflush(stdout);
  85.  
  86.     for (i = 0; i < f && err < ERROR; i++)
  87.     {
  88.         fclose(files[i]);
  89.         if (errno != 0) err = ERROR;
  90.     }
  91.     if (err >= ERROR) perror("tee failed");
  92.     /* Any files left open will be closed */
  93.     exit(err);
  94. }
  95.  
  96.